﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace WebApplication4
{
    public class SqlHelp
    {
        private static string constr = "server=.;uid=sa;pawd=123456;database=Student_db";
        private SqlConnection con = null;
        public SqlHelp()
        {
            con = new SqlConnection();
        }
        //执行数据库查询操作
        public DataTable Get(string sql,SqlParameter[] pars)
        {
            try
            {
                if (con.State==ConnectionState.Closed)
                {
                    con.Open();
                }

                SqlCommand cmd = new SqlCommand(sql, con);
                if (pars!=null && pars.Length!=0)
                {
                    cmd.Parameters.Add(pars);
                }
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (con!=null)
                {
                    con.Close();
                }
            }
        }
        //执行数据库非查询操作
        public bool Execute(string sql,SqlParameter []pars)
        {
            try
            {
                if (con.State==ConnectionState.Closed)
                {
                    con.Open();
                }
                SqlCommand cmd = new SqlCommand(sql, con);
                if (pars != null && pars.Length!=0)
                {
                    cmd.Parameters.AddRange(pars);
                }
                return cmd.ExecuteNonQuery() > 0;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (con!=null)
                {
                    con.Close();
                }
            }
        }
    }
}